package client.connect;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;



import client.Client;

public class PanelConnection extends JPanel {
	
	private JLabel labelName;
	private JTextField textFieldName;
	private JButton buttonConnect;
	private JButton buttonDisconnect;
	
	private FrameConnect frame;

	public PanelConnection(FrameConnect frame) {
		
		this.frame = frame;
		
		setBackground(Color.LIGHT_GRAY);
		setMinimumSize(new Dimension(400, 35));
		setPreferredSize(new Dimension(400, 35));
		setLayout(new FlowLayout());
		
		//label
		labelName = new JLabel("Enter your username: ");
		
		//textField
		textFieldName = new JTextField();
		textFieldName.setPreferredSize(new Dimension(100, 20));
		
		//buttonConnect
		buttonConnect = new JButton(new ImageIcon("source/_images/Connect.png"));
		buttonConnect.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String username = textFieldName.getText();
				getFrame().client = new Client(username, getFrame());
				getFrame().client.run();
				
				
				List <String> users = getFrame().client.getAllParticipant();
				updateUsers(users);
				
			}
		});
		
		//buttonDisconnect
		buttonDisconnect = new JButton(new ImageIcon("source/_images/Disconnect.png"));
		buttonDisconnect.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				
			}
		});
		buttonDisconnect.setEnabled(false);
		
		add(labelName);
		add(textFieldName);
		add(buttonConnect);
		add(buttonDisconnect);
		
		setVisible(true);
	}
	
	private String traitementParticipants(Hashtable<String, InetSocketAddress> membres) {
		String s = "";
		Enumeration<String> keys = membres.keys();
		while(keys.hasMoreElements()){
			String nom = keys.nextElement();
			s += nom + ";";
		}
		
		return s;
	}
	
	public FrameConnect getFrame() {
		return this.frame;
	}
	private void updateUsers(List <String>  users) {
		this.frame.updateUserList(users);
	}
}
